package com.frinder.hadoop.hbase.original;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

/**
 * @author frinder
 * @date 2018/6/30
 * @Description: 需要 resource 目录下的 hbase-site.xml 文件
 */
public class HBasePooledObjectFactory implements PooledObjectFactory<Connection> {

    protected static Configuration configuration;

    static {
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum", "master");
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
    }

    @Override
    public PooledObject<Connection> makeObject() throws Exception {
        Connection connection = ConnectionFactory.createConnection(configuration);
        return new DefaultPooledObject<>(connection);
    }

    @Override
    public void destroyObject(PooledObject<Connection> pooledObject) throws Exception {
        Connection connection;
        if (null != (connection = pooledObject.getObject()) && !connection.isClosed()) {
            connection.close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<Connection> pooledObject) {
        Connection connection;
        return null != (connection = pooledObject.getObject()) && !connection.isClosed();
    }

    @Override
    public void activateObject(PooledObject<Connection> pooledObject) throws Exception {
    }

    @Override
    public void passivateObject(PooledObject<Connection> pooledObject) throws Exception {
    }
}
